import React, { useState, useEffect } from 'react'
import { Avatar, Typography, Space } from '@arco-design/web-react';
import { Button, Badge, Swiper, NavBar, Toast } from 'react-vant'
import { MoreO } from '@react-vant/icons'
import { useNavigate } from 'react-router-dom';
import { FixedSizeGrid as Grid } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
import Mock from 'mockjs'
import { LazyLoadImage } from 'react-lazy-load-image-component'
import 'react-lazy-load-image-component/src/effects/blur.css'

// 模拟商品数据
const mockProducts = Mock.mock({
  'products|4': [{
    'id|+1': 1,
    'name': '@ctitle(5, 10)',
    'price': '@float(100, 1000, 2, 2)',
    'image': '@image("200x200", "#50B347", "#FFF", "Product")',
    'description': '@cparagraph(1, 2)',
    'rating|1-5': 5,
    'sales|100-1000': 100
  }]
}).products

interface Product {
  id: number
  name: string
  price: number
  image: string
  description: string
  rating: number
  sales: number
}

// 商品卡片组件
const ProductCard = React.memo(({ product }: { product: Product }) => {
    const navigate = useNavigate()
  return (
  <div style={{
    border: '1px solid #eee',
    borderRadius: '8px',
    padding: '10px',
    height: '100%',
    boxSizing: 'border-box',
    backgroundColor: '#fff',
    transition: 'all 0.3s ease',
    cursor: 'pointer'
  }} >
    <LazyLoadImage
      src={product.image}
      alt={product.name}
      effect="blur"
      placeholderSrc=""
      style={{
        width: '100%',
        height: '200px',
        objectFit: 'cover',
        borderRadius: '4px'
      }}
      wrapperClassName="lazy-load-image-wrapper"
    />
    <h4 style={{ margin: '10px 0' }} onClick={()=>{
    navigate('/detailCar',{state:product})
  }}>{product.name}</h4>
    <p style={{ color: '#666', fontSize: '14px' }}>{product.description}</p>
    <div style={{ 
      display: 'flex', 
      justifyContent: 'space-between', 
      alignItems: 'center',
      marginTop: '10px'
    }}>
      <span style={{ color: '#f00', fontSize: '18px', fontWeight: 'bold' }}>
        ¥{product.price}
      </span>
      <span style={{ color: '#999', fontSize: '12px' }}>
        已售 {product.sales}
      </span>
    </div>
    <div style={{ marginTop: '5px' }}>
      {Array(5).fill('★').map((star, index) => (
        <span 
          key={index} 
          style={{ 
            color: index < product.rating ? '#ffd700' : '#ddd',
            fontSize: '14px'
          }}>
          {star}
        </span>
      ))}
    </div>
  </div>
)
})

export default function Shou() {
    const [imglist, setImglist] = useState<Array<string>>([
        'https://fastly.jsdelivr.net/npm/@vant/assets/apple-1.jpeg',
        'https://fastly.jsdelivr.net/npm/@vant/assets/apple-2.jpeg',
    ])
    const [isLoggedIn, setIsLoggedIn] = useState(localStorage.getItem('isLogin') === 'yes');
    const [products] = useState<Product[]>(mockProducts)
    const [username, setUsername] = useState('');
    const router = useNavigate()
    const [lastResult, setLastResult] = useState<any>(null);

    useEffect(() => {
        const storedUsername = localStorage.getItem('username');
        if (storedUsername) {
            setUsername(storedUsername);
            setIsLoggedIn(true);
        } else {
            setIsLoggedIn(false);
        }
        // 读取本地存储的皮肤测试结果
        const resultStr = localStorage.getItem('pifuresult');
        if (resultStr) {
            try {
                setLastResult(JSON.parse(resultStr));
            } catch {
                setLastResult(null);
            }
        } else {
            setLastResult(null);
        }
    }, []);

    // 虚拟列表配置
    const COLUMN_COUNT = 2
    const ROW_HEIGHT = 400
    const COLUMN_WIDTH = 300

    const gotopage = () => {
        console.log(isLoggedIn,'isLoggedIn');
        
        if (isLoggedIn) {
            router('/app/ska')
        } else {
            Toast('请先登录');
            router('/login');
        }
    }

    // 虚拟列表单元格渲染
    const Cell = ({ columnIndex, rowIndex, style }: { columnIndex: number, rowIndex: number, style: React.CSSProperties }) => {
        const index = rowIndex * COLUMN_COUNT + columnIndex
        if (index >= products.length) return null

        return (
            <div style={{
                ...style,
                padding: '10px'
            }}>
                <ProductCard product={products[index]} />
            </div>
        )
    }

    return (
        <div>
            <div style={{ margin: '24px 16px 0 16px' }}>
                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 8 }}>
                    <Avatar style={{ background: '#000', marginRight: 8 }} size={48} onClick={() => { router('/my') }}>
                        <img
                            alt='avatar'
                            src='https://img.icons8.com/ios-filled/50/000000/user-male-circle.png'
                            style={{ filter: 'brightness(0)' }}
                        />
                    </Avatar>
                    <span style={{ fontSize: 18, fontWeight: 500 }}>您好,{isLoggedIn ? username : '请先登录'} <span role="img" aria-label="wave">👋</span></span>
                    <Button style={{ marginLeft: 'auto', background: '#fff', border: 'none', boxShadow: '0 0 4px #eee' }} icon={<MoreO />} />
                </div>
                <div style={{ fontSize: 28, fontWeight: 600, lineHeight: 1.2, margin: '16px 0 0 0' }}>让我们一起呵护<br />您的肌肤</div>
                <div style={{ background: '#fff', borderRadius: 16, boxShadow: '0 2px 8px #f0f1f2', padding: 20, margin: '24px 0 0 0' }}>
                    {isLoggedIn ? (
                        lastResult ? (
                            <>
                                <div style={{ display: 'flex', alignItems: 'center', marginBottom: 12 }}>
                                    <img src="https://img.icons8.com/ios/50/4a90e2/leaf.png" alt="leaf" style={{ width: 20, marginRight: 8 }} />
                                    <span style={{ fontWeight: 500 }}>皮肤测试得分 {lastResult.skin_score ? lastResult.skin_score + '%' : '--'}</span>
                                    <span style={{ color: '#999', fontSize: 12, marginLeft: 8 }}>{lastResult.time ? (new Date(lastResult.time).toLocaleDateString()) : ''}</span>
                                </div>
                                <div>
                                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 16 }}>
                                    {lastResult.conclusion && lastResult.conclusion.length > 0 ? (
                                        lastResult.conclusion.slice(0, 4).map((item: any) => {
                                            const emojiMap: Record<string, string> = {
                                                '细腻度': '🌸',
                                                '匀净度': '🌙',
                                                '紧致度': '🌿',
                                                '耐受度': '❄️'
                                            };
                                            const icon = emojiMap[item.name] || '';
                                            return (
                                                <div key={item.cid} style={{ background: '#faf7fd', borderRadius: 12, padding: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
                                                    <span role="img" aria-label="icon">{icon}</span>
                                                    <span style={{ flex: 1 }}>{item.name}</span>
                                                    <span style={{ fontWeight: 500 }}>{item.score ? item.score + '%' : '--'}</span>
                                                </div>
                                            );
                                        })
                                    ) : (
                                        <div style={{ gridColumn: '1/3', textAlign: 'center', color: '#aaa' }}>暂无详细数据</div>
                                    )}
                                </div>
                                <Button onClick={() => { gotopage() }} style={{ width: '100%', background: '#7356f1', color: '#fff', fontWeight: 500, fontSize: 16, borderRadius: 8, marginTop: isLoggedIn ? 0 : 16 }}>现在检查</Button>
                                </div>
                            </>
                        ) : (
                            <div style={{ textAlign: 'center', color: '#aaa', marginBottom: 16 }}>暂无皮肤测试数据</div>
                        )
                    ) : (
                        <Swiper autoplay={3000}>
                            {imglist.map((item, index) => (
                                <Swiper.Item key={index}>
                                    <img src={item} alt={`slide-${index}`} style={{ width: '100%', display: 'block', borderRadius: 12 }} />
                                </Swiper.Item>
                            ))}
                        </Swiper>
                    )}
                </div>
                <div style={{ margin: '32px 0 0 0', fontWeight: 500, fontSize: 18, display: 'flex', alignItems: 'center' }}>
                    活动
                    <span style={{ color: '#7356f1', fontSize: 14, marginLeft: 'auto', cursor: 'pointer' }}>查看全部</span>
                </div>
                <div style={{ background: '#fff', borderRadius: 12, boxShadow: '0 2px 8px #f0f1f2', padding: 16, margin: '16px 0 0 0', display: 'flex', alignItems: 'center', gap: 12 }} onClick={() => { gotopage() }}>
                    <img src="https://img.icons8.com/ios/50/4a90e2/face-id.png" alt="face" style={{ width: 32 }} />
                    <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 500 }}>人脸分析</div>
                        <div style={{ color: '#999', fontSize: 12 }}>拍摄您的脸部照片以分析脸部特征</div>
                    </div>
                    <img src="https://img.icons8.com/ios/50/4a90e2/leaf.png" alt="leaf" style={{ width: 20 }} />
                </div>
                <div style={{ margin: '32px 0 0 0', fontWeight: 500, fontSize: 18, display: 'flex', alignItems: 'center' }}>
                    推荐
                    <span style={{ color: '#7356f1', fontSize: 14, marginLeft: 'auto', cursor: 'pointer' }} onClick={() => { router('/list') }}>查看全部</span>
                </div>
                
                {/* 虚拟列表商品展示 */}
                <div style={{ marginTop: '20px', height: '600px' }}>
                    <div style={{ height: '100%' }} >
                        <AutoSizer>
                            {({ height, width }) => (
                                <Grid
                                    columnCount={COLUMN_COUNT}
                                    columnWidth={COLUMN_WIDTH}
                                    height={height}
                                    rowCount={Math.ceil(products.length / COLUMN_COUNT)}
                                    rowHeight={ROW_HEIGHT}
                                    width={width}>
                                    {Cell}
                                </Grid>
                            )}
                        </AutoSizer>
                    </div>
                </div>
            </div>
        </div>
    )
}
